<template>
  <!-- 添加和修改章节表单 -->
  <!--  -->
  <el-dialog
    :visible="dialogVisible"
    :title="title"
    @close="close()"
    :before-close="handleBefore"
  >
    <el-form :model="chapter" label-width="120px">
      <el-form-item label="章节标题">
        <el-input v-model="chapter.title" />
      </el-form-item>
      <el-form-item label="章节排序">
        <el-input-number v-model="chapter.sort" :min="0" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取 消</el-button>
      <el-button type="primary" @click="saveOrUpdate()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import chapterApi from "@/api/chapter.js";
export default {
  data() {
    return {
      title: "添加章节",
      dialogVisible: false,
      chapter: {
        sort: 0,
      },
    };
  },
  methods: {
    open(chapterId) {
      if (chapterId) {
        //编辑回显
        chapterApi.getChapter(chapterId).then((response) => {
          this.chapter = response.data.item;
          this.dialogVisible = true;
        });
      } else {
        //新增
        this.dialogVisible = true;
      }
    },

    close() {
      this.dialogVisible = false;
      //重置form表单 解决 在点击编辑后再点击添加章节会回显
      this.formReset();
    },

    saveOrUpdate() {
      //无chapterId即新增操作
      if (!this.chapter.id) {
        this.save();
      } else {
        //有chapterId即更新操作
        this.update();
      }
      this.formReset();
    },
    //重置提交的新增章节表单数据
    formReset() {
      this.chapter = {
        sort: 0,
      };
    },
    save() {
      //给chapter对象设置章节所属的课程id
      this.chapter.courseId = this.$parent.$parent.courseId;
      console.log("新增章节: ");
      console.log(this.chapter);
      chapterApi.saveChapter(this.chapter).then((response) => {
        //this.chapter.id = response.data.chapterId
        this.$message.success(response.message);
        //调用父组件的查询章节课时嵌套集合的方法,即添加后回显数据
        this.$parent.getChapterNestedList();
      });
      this.close();
    },

    update() {
      chapterApi.updateChapter(this.chapter).then((response) => {
        this.$message.success(response.message);
        //调用父组件的查询章节课时嵌套集合的方法,即更新后回显数据
        this.$parent.getChapterNestedList();
      });
      this.close();
    },
    //点击边框外不关闭
    handleBefore() {},
  },
};
</script>